package com.aifeng.hassan_food

import android.annotation.SuppressLint
import android.graphics.Paint
import android.os.Bundle
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.GridLayoutManager
import com.aifeng.base.*
import com.aifeng.common_ui.base.gone
import com.aifeng.common_ui.base.oneClick
import com.aifeng.common_ui.base.visible
import com.aifeng.common_ui.helper.*
import com.aifeng.hassan_food.login.LoginActivity
import com.aifeng.hassan_food.sale.DetailActivity
import com.aifeng.model.GoodsData
import com.aifeng.oss.scaleImage
import com.aifeng.utils.GridGapDecoration
import com.aifeng.utils.bindLifeCycle
import com.aifeng.utils.subscribeByFinally
import com.aifeng.utils.subscribeByNoError
import com.aifeng.viewmodel.GoodsViewModel
import com.jeremyliao.liveeventbus.LiveEventBus
import com.jeremyliao.liveeventbus.utils.observe
import kotlinx.android.synthetic.main.layout_empty.*
import kotlinx.android.synthetic.main.layout_list.*
import kotlinx.android.synthetic.main.layout_title_search.*
import net.idik.lib.slimadapter.SlimAdapter
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.toast
import org.koin.androidx.viewmodel.ext.android.getViewModel

class SearchActivity : BaseActivity() {

    private var mKey = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_search)
        setToolbarVisibility(isVisible = false)
        initTitle()
    }

    override fun getViewModel() = getViewModel<GoodsViewModel>()

    @SuppressLint("SetTextI18n")
    override fun initTitle(title: String, name: String, divider: Boolean) {
        search_edit.hint = "请输入关键字"
        empty_hint.text = "暂无相关商品信息！"
        swipe_refresh.refresh { getData(1) }
        recycle_list.loadGrid(swipe_refresh, {
            if (!isLoadingMore) {
                isLoadingMore = true
                getData(pageNum)
            }
        }) {
            layoutManager = GridLayoutManager(baseContext, 2)
            addItemDecoration(GridGapDecoration(horizontal = 12, vertical = 8))
            mAdapter = SlimAdapter.create()
                .register<GoodsData>(R.layout.item_three_grid) { inner, jector ->
                    jector.text(R.id.item_three_name, inner.goodname)
                        .text(
                            R.id.item_three_price,
                            setHtmlSmall(
                                "¥ ${if (isLogin) inner.price.formatDecimal() else inner.orgprice.formatDecimal()}",
                                "¥"
                            )
                        )
                        .with<TextView>(R.id.item_three_orgin) {
                            it.paint.flags = Paint.STRIKE_THRU_TEXT_FLAG
                            it.text = "¥ ${inner.orgprice.formatDecimalWhenHave()}"
                        }
                        .with<ImageView>(R.id.item_three_img) {
                            val imgs = inner.goodimg.split(",")
                            it.loadImage(url = imgs[0].scaleImage(320, 320))
                        }
                        .visibility(
                            R.id.item_three_orgin,
                            if (isLogin) View.VISIBLE else View.GONE
                        )
                        .visibility(
                            R.id.item_three_set,
                            if (inner.specstype == "package") View.VISIBLE else View.GONE
                        )
                        .clicked(R.id.item_three_add) {
                            if (isLogin) {
                                getViewModel().addToCar(
                                    inner.id,
                                    getString("userId"),
                                    1
                                )
                                    .bindLifeCycle(getLifecycleOwner())
                                    .subscribeByNoError(
                                        event = getViewModel(),
                                        onSuccess = {
                                            toast("添加商品成功！")
                                            LiveEventBus.get("carList").post("refresh")
                                            LiveEventBus.get("updateNum").post(it)
                                        }
                                    )
                            } else {
                                startActivity<LoginActivity>()
                            }
                        }
                        .clicked(R.id.item_three) {
                            startActivity<DetailActivity>("id" to inner.id)
                        }
                }
                .attachTo(this)

            observe("otherLogin") { mAdapter.notifyDataSetChanged() }
        }

        search_right.oneClick { search() }
        search_close.oneClick { search_edit.setText("") }
        search_edit.addTextChangedListener(this)
        search_edit.setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH) search()
            return@setOnEditorActionListener false
        }
    }

    private fun search() {
        hideSoftInput() //隐藏软键盘

        if (search_edit.text.isBlank()) {
            toast("请输入关键字")
        } else {
            mKey = search_edit.trimString()
            updateList()
        }
    }

    private fun updateList() {
        swipe_refresh.isRefreshing = true

        empty_view.gone()
        if (mList.isNotEmpty()) {
            mList.clear()
            mAdapter.notifyDataSetChanged()
        }

        pageNum = 1
        getData(pageNum)
    }

    override fun getData(index: Int, isLoading: Boolean) {
        if (mKey.isNotEmpty()) {
            getViewModel().getGoodsList(
                page = index,
                name = mKey
            )
                .bindLifeCycle(getLifecycleOwner())
                .subscribeByFinally(
                    event = getViewModel(),
                    onSuccess = {
                        mList.apply {
                            if (index == 1) {
                                clear()
                                pageNum = index
                            }
                            addItems(it)
                            if (count(it) > 0) pageNum++
                        }

                        mAdapter.updateData(mList)
                    },
                    onFinally = {
                        swipe_refresh.isRefreshing = false
                        isLoadingMore = false
                        empty_view.apply { if (mList.isEmpty()) visible() else gone() }
                    }
                )
        } else {
            swipe_refresh.isRefreshing = false
        }
    }

    override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
        search_close.visibility = if (s.isEmpty()) View.GONE else View.VISIBLE
        if (s.isEmpty() && mKey.isNotEmpty()) {
            mKey = ""
            empty_view.gone()
            if (mList.isNotEmpty()) {
                mList.clear()
                mAdapter.notifyDataSetChanged()
            }
        }
    }

}
